<template>
  <div>
    <div class="popup-container month_popup" v-show="popupState.showStatusMonthly">
      <div class="popup max" style="margin: 1% 0;">
        <i class="el-icon-error icon_close" @click="closePopup"></i>
        <div class="title">{{popupState.popupNameMonthly}}</div>

        <div class="content" style="padding: 0 20px 10px 20px">
          <el-form :disabled="previewStatus" :model="formDataMonth" ref="monthRules"  label-position="left"  style=""
            :inline='true' class="form">
            <div style="overflow:hidden">
              <div style="padding-left: 50px; position: relative;display: flex;">
                <el-form-item size="small"  prop="schoolId" class="fl" label="校区选择" style="width: 20%; margin-bottom: 15px; margin-right: 2%">
                  <el-select :disabled="updateStatus" @change="(e) => changeMonthSchool(e, true)" style="width: 130px;" v-model="formDataMonth.schoolId" placeholder="校区">
                    <el-option v-for="(item,key) in schoolList" :key="key" :label="item.schoolName" :value="item.schoolId">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item size="small" prop="financialYear" class="fl" label="学年" style="width: 16%;margin-bottom: 15px; margin-right: 2%">
                  <el-date-picker
                    :disabled="updateStatus"
                    style="width: 105px"
                    value-format="yyyy"
                    format="yyyy年"
                    v-model="formDataMonth.financialYear"
                    type="year"
                    @change="changeYear"
                    placeholder="学年">
                  </el-date-picker>
                </el-form-item>

                <el-form-item size="small" prop="financialMonth" class="fl" label="月度" style="width: 14%;margin-bottom: 15px; margin-right: 2%">
                  <el-date-picker
                    style="width: 95px"
                    :disabled="updateStatus"
                    @change="changeMonth"
                    v-model="formDataMonth.financialMonth"
                    value-format="MM"
                    format="M月"
                    type="month"
                    placeholder="月度">
                  </el-date-picker>
                </el-form-item>

                <div class="fl" style="font-size: 12px; line-height: 32px; ">
                  <span style="margin-left: 15px;">年度本月签单：{{schoolInfo.monthTargetNumber || ''}} 人</span>
                  <span style="margin-left: 150px;">年度本月金额：{{schoolInfo.monthTargetPrice || ''}} 元</span>
                </div>
                <div class="clear"></div>
              </div>

              <div class="data_list">
                <div class="data_item">
                  <span>本期签单</span>
                  <span class="num">{{computedWeekData.number}}</span> 人
                </div>
                <div class="data_item">
                  <span>本期金额</span>
                  <span class="num">{{computedWeekData.price}}</span> 元
                </div>
                <div class="data_item">
                  <span>本月实设签单</span>
                  <span class="num">{{computedMonthData.number}}</span> 人
                </div>
                <div class="data_item">
                  <span>本月金额</span>
                  <span class="num">{{computedMonthData.price}}</span> 元
                </div>
              </div>
              

              <el-tabs 
                v-model="activeName_month" 
                tab-position="left" 
                type="card" 
                @tab-click="handleClick"
              >
              <!-- -->
                
                <el-tab-pane v-for="(item, index) in formDataMonth.periodsList"  :key="index" :label="`第${index+1}期`"  :name="`tab${index}`">
                  <slot slot="label">
                    <span class="tab_title">{{`第${index+1}期`}}</span>
                    <span class="tab_title">({{weekNameArr[index]}}天)</span>
                  </slot>

                  <div class="product_list" >
                    <div class="fl">
                      <div class="product_item" v-for="(productItem, productIndex) in item.periodsItem" :key="productIndex">
                        <div class="line_item fl">
                          <!-- 课程产品 -->
                          <div class="product_info ">
                            <div class="fl">
                              <el-form-item >
                                <span slot="label">课程{{productIndex+1}}</span>
                                <el-select :disabled="updateStatus" size="mini" @change="(e) => changeProduct(e, index, productIndex)" v-model="productItem.productId" style="width: 100px;" placeholder="课程产品">
                                  <el-option v-for="(item,key) in productList" :key="key" :label="item.productCode + '-' + item.productName" :value="item.productId">
                                  </el-option>
                                </el-select>
                              </el-form-item>
                              <span class="product_price">单价 : {{productItem.productPrice}}元</span>
                              <span class="" style="margin-right: 2px;">尚余 : {{productItem.remainingNum}} 人</span>
                              <div class="clear"></div>
                              <div style="height: 30px; line-height: 30px;">
                                <span class="rectangle">人数</span>
                                <el-form-item  style="margin-right: 5px;">
                                  <el-input @change="(e) => computedRemainingNum(e, index, productIndex)" v-model="productItem.totalNumber" size="mini" style="width: 48px;"></el-input>
                                </el-form-item>
                                <span class="rectangle">金额：{{computedProductTotalPrice(index, productIndex)}}元</span>
                                <span class="hasColor" @click="checkRate(index, productIndex)">转化率>></span>
                              </div>

                            </div>
                            <div class="clear"></div>
                          </div>
                          <!-- 课程顾问 -->
                          <div class="person_list fl">
                            <div>
                              <div class="person_item" v-for="(personItem, personIndex) in productItem.peopleList" :key="personIndex">
                                <el-form-item label="课程顾问">
                                  <el-select @change="(e) => changePerson(e, index, productIndex, personIndex)" :disabled="updateStatus" size="mini" v-model="personItem.employeesId" style="width: 110px;" placeholder="课程顾问">
                                    <el-option v-for="(item,key) in personList" :key="key" :label="item.employeesName" :value="item.employeesId">
                                    </el-option>
                                  </el-select>
                                </el-form-item>
                                <div class="clear"></div>
                                <el-form-item label="人数" style="margin-right: 0px;">
                                  <el-input @change="(e) => changePersonNum(e, index, productIndex, personIndex)" v-model="personItem.fullNumber" size="mini" style="width: 48px;"></el-input>
                                </el-form-item>
                                <span class="hasColor" @click="personDetail(index, productIndex, personIndex)" style="line-height: 30px;">详情>></span>
                                <span class="item_price">金额 : {{computedPersonTotalPrice(index, productIndex, personIndex)}}</span>
                                <!-- <span class="item_price">金额 : {{personItem.weekTargetPrice}}</span> -->
                                <div v-if="!updateStatus" class="inline_icon_box">
                                  <span @click="addPerson(index, productIndex, personIndex)" v-if="personIndex == productItem.peopleList.length - 1" class="el-icon-plus"></span>
                                  <span @click="removePerson(index, productIndex, personIndex)" class="el-icon-minus"></span>
                                </div>
                              </div>
                              <div v-if="!updateStatus" class="icon_box">
                                <span @click="removeProduct(index, productIndex)" class="el-icon-remove-outline"></span>
                                <span @click="addMonthProduct(index, productIndex)" v-if="productIndex == item.periodsItem.length - 1" class="el-icon-circle-plus-outline"></span>
                              </div>
                              
                            </div>
                          </div>
                          <div class="clear"></div>
                        </div>
                        <div class="clear"></div>
                      </div>
                    </div>
                  </div>
                </el-tab-pane>
              </el-tabs>

              <div class="clear"></div>

            </div>

          </el-form>

          <div class="btn_box" style="margin-top: 10px;">
            
            <div class="btn btn_add" v-if="popupState.popupNameMonthly == '新建月度目标'  && !previewStatus" @click="saveData" style="margin-right: 20px;">
              <span class="btn_txt">保存</span>
            </div>

            <div class="btn btn_add" v-if="popupState.popupNameMonthly == '新建月度目标'  && previewStatus" @click="previewStatus = false;" style="margin-right: 20px;">
              <span class="btn_txt">返回修改</span>
            </div>



            <div class="btn btn_add" @click="previewPage" v-if="popupState.popupNameMonthly == '新建月度目标' && !previewStatus">
              <span class="btn_txt">预览</span>
            </div>
            <div class="btn btn_add" v-if="popupState.popupNameMonthly == '新建月度目标' && previewStatus" @click="submitAddMonth('ruleForm')">
              <span class="btn_txt">提交</span>
            </div>

            <div class="btn btn_add" v-if="popupState.popupNameMonthly == '编辑月度目标'" @click="submitEditMonthPeople('ruleForm')">
              <span class="btn_txt">提交</span>
            </div>



          </div>

        </div>
      </div>
    </div>

    <div  v-show="showCheckRate" class="popup-container">
      <div class="popup mini" style="top: 0">
        <i class="el-icon-error icon_close" @click="showCheckRate = false"></i>
        <div class="title">转换率</div>
        <div class="content">
          <el-form :model="rateInfo" label-width="140px" disabled  label-position="left">
            <el-form-item size="small" class="fl" label="有效单 > 试听(%) : " >
              <el-input style="width: 200px;"  v-model="rateInfo.auditionRate" autocomplete="off" placeholder=""></el-input>
            </el-form-item>
            <div class="clear"></div>
            <el-form-item size="small" class="fl" label="试听 >  定金(%) :" >
              <el-input style="width: 200px;" v-model="rateInfo.earnestRate" autocomplete="off" placeholder=""></el-input>
            </el-form-item>
            <div class="clear"></div>
            <el-form-item size="small" class="fl" label="定金 > 签单(%) : " >
              <el-input style="width: 200px;" v-model="rateInfo.signRate" autocomplete="off" placeholder=""></el-input>
            </el-form-item>
          </el-form>
          <div class="clear"></div>
          
        </div>
      </div>
    </div>

    <div  v-show="showPersonDetail" class="popup-container">
      <div class="popup mini" style="top: 0">
        <i class="el-icon-error icon_close" @click="showPersonDetail = false"></i>
        <div class="title">详情</div>
        <div class="content">
          <el-form :model="rateInfo" label-width="100px" disabled  label-position="left">
            <el-form-item size="small" class="fl" label="有效单(人) : " >
              <el-input style="width: 200px;"  v-model="detailInfo.effectiveSingular" autocomplete="off" placeholder=""></el-input>
            </el-form-item>
            <div class="clear"></div>
            <el-form-item size="small" class="fl" label="试听(人) :" >
              <el-input style="width: 200px;" v-model="detailInfo.auditionNum" autocomplete="off" placeholder=""></el-input>
            </el-form-item>
            <div class="clear"></div>
            <el-form-item size="small" class="fl" label="定金(人) : " >
              <el-input style="width: 200px;" v-model="detailInfo.earnestNum" autocomplete="off" placeholder=""></el-input>
            </el-form-item>
            <div class="clear"></div>
            <el-form-item size="small" class="fl" label="签单(人) : " >
              <el-input style="width: 200px;" v-model="detailInfo.fullNumber" autocomplete="off" placeholder=""></el-input>
            </el-form-item>
          </el-form>
          <div class="clear"></div>
          
        </div>
      </div>
    </div>


  </div>
</template>

<style>
.month_popup .el-tabs__nav > div {
  padding: 5px 4px !important;
  display: inline-block;
}
.month_popup .el-tabs__nav > div span {
  font-size: 11px !important;
}
.month_popup .el-input--mini .el-input__inner,
.month_popup .el-input--mini .el-input__icon {
  height: 25px !important;
  line-height: 25px !important;
}
.month_popup .el-form-item__content, .month_popup .el-form-item__label {
  line-height: 30px !important;
}
.month_popup .el-form-item__label {
  font-size: 12px !important;
}


.month_popup .el-tabs--left .el-tabs__header.is-left {
  margin-right: 0;
}

.month_popup .el-tabs__content{
  padding-top: 0 !important;
  min-height: 300px;
  box-shadow: none !important;
  border-left: none !important;
  background: #F5F7FA !important;
}


.month_popup .el-form-item {
  margin-bottom: 0 !important;
  margin-right: 0px;
}

.max {
  width: 85% !important;
  left: calc(47% + 100px) !important;
}
</style>
<style scoped>
.tab_title{
  display: block;
  text-align: center;
  line-height: 20px;
}
.month_popup .popup .title {
  border-bottom: none !important;
}
.month_popup .inline_icon_box{
  position: absolute;
  right: 3px;
  top: 5px;
}
.month_popup .inline_icon_box span{
  display: block;
  color: #87AEFF;
  cursor: pointer;
  font-size: 10px !important;
}
.month_popup .inline_icon_box span:last-child {
  margin-top: 4px;
}

.month_popup .item_price {
  color: #606266;
  font-size: 11px !important;
  line-height: 30px !important;
}
.month_popup .product_list {
  padding: 5px;
  box-sizing: border-box;
  /* overflow-x: scroll; */
  white-space:nowrap;
  overflow-x:auto;
  overflow-y:hidden;
}
.month_popup .product_item {
  /* position: relative; */
  background: #fff;
  /* padding-left: 5px; */
  border:1px solid rgba(231,231,231,1);
  border-bottom: none;
  padding: 8px 5px;
  /* margin-bottom: 5px; */
  /* width: 1200px; */
}
.month_popup .product_item:last-child {
  border-bottom:1px solid rgba(231,231,231,1);
}
.month_popup .line_item {
  /* width: 100%; */
  /* overflow: hidden; */
  /* overflow-x: auto; */
  position: relative;
}
.month_popup .icon_box{
  /* position: absolute; */
  display: inline-block;
}
.month_popup .icon_box span {
  display: block;
  color: #87AEFF;
  cursor: pointer;
  font-size: 13px !important;
  margin: 12px 0;
}
.month_popup .person_list {
  /* overflow: hidden; */
  margin-left: 10px;
  /* position: absolute; */
  padding-left: 285px;
}
.month_popup .product_info{
  float: left;
  position: absolute;
  left: 0;
  z-index: 999;
  background: #fff;
}
.month_popup  .person_item {
  /* float: left; */
  position: relative;
  display: inline-block;
  background: #FAFBFF;
  border-radius:7px;
  box-shadow:0px 0px 0px 2px rgba(242,242,242,0.5);
  padding: 0 5px;
  box-sizing: border-box;
  margin: 0 8px;
  width: 205px;
}
.month_popup span {
  font-size: 12px !important;
}
.month_popup .hasColor {
  color: #77A4FF;
  font-size: 10px !important;
  cursor: pointer;
}
.month_popup .product_price {
  line-height: 30px;
  width: 82px;
  display: inline-block;
}
.month_popup .rectangle{
  background:linear-gradient(180deg,rgba(255,255,255,0.5) 0%,rgba(188,188,188,0.5) 100%);
  border-radius:3px;  
  border:1px solid rgba(220,221,223,1);
  padding: 3px 10px;
  box-sizing: border-box;
  color: #5d5d5d;
}
.data_list {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
  padding-left: 50px;
}
.data_list .data_item {
  background: #ECEDEE;
  line-height: 28px;
  border-radius: 3px;
  font-size: 11px;
  padding: 0 10px;
  box-sizing: border-box;
  width: 200px;
  text-align: center;
}
.data_list .data_item .num {
  background: #fff;
  border-radius: 3px;
  padding: 0 20px;
  line-height: 22px;
  display: inline-block;
  box-sizing: border-box;
  margin-left: 5px;
  margin-right: 5px;
}
</style>

<script>
import {
  createNamespacedHelpers,
  mapState,
} from "vuex";
let {
  // mapState,
  mapGetters,
  mapMutations,
  mapActions
} = createNamespacedHelpers("targetSetting");

export default {
  name: 'targetSetting_monthPopup',
  data() {
    return {
      activeName_month: 'tab0',
      updateStatus: false,
      showCheckRate: false,
      showPersonDetail: false,
      previewStatus: false,
      jwtAuth: {},
      schoolInfo: {},
      productList: [],
      personList: [],
      schoolList: [],
      powerSchoolList: [],
      rateInfo: {
        auditionRate: 0,
        earnestRate: 0,
        signRate: 0,
      },
      detailInfo: {
        audition: 0,
        earnest: 0,
        sign: 0,
      },

      weekDateArr: [],
      weekNum: 1,
      currentWeek: 0,

      monthDiffValue: {
        number: 0,
        price: 0,
      },

      weekTargetArr: [],
      weekCurrentArr: [],
      weekDiffArr: [],
      weekNameArr: [],
      originProductNumber: 0,

      copyWeekArr: []
    }
  },
  watch: {
    'popupState.popupNameMonthly'(newVal, oldVal) {
      if(newVal == '新建月度目标') {
        this.updateStatus = false;
      }else{
        this.updateStatus = true;
      }
    },

    "popupState.showStatusMonthly"(newVal, oldVal) {
      this.previewStatus = false;
    },

    isUpdateMonth() {
      this.activeName_month = 'tab0'
      this.currentWeek = 0
      this.previewStatus = false;

      console.log(this.isUpdateMonth)
      this.originProductNumber = 0;
      
      this.changeMonthSchool(this.formDataMonth.schoolId);
      // console.log(this.formDataMonth)
      // this.changeProduct()
      
      setTimeout(() => {
        let monthCurrentData = {
          number: 0,
          price: 0,
        }
        this.formDataMonth.periodsList.forEach((periodsItem, periodsIndex) => {
          periodsItem.periodsItem.forEach((productItem, productIndex) => {
            monthCurrentData.number += Number(productItem.totalNumber);
            monthCurrentData.price  += (Number(productItem.productPrice) * Number(productItem.totalNumber));
          })
        })
        let targetMonthData = {
          number: Number(this.formDataMonth.totalNumberMonth),
          price: Number(this.formDataMonth.totalPriceMonth),
        };

        this.monthDiffValue = {
          number: targetMonthData.number - monthCurrentData.number,
          price: targetMonthData.price - monthCurrentData.price,
        };

        /* ================================ */
      }, 0)

      

      this.weekTargetArr = [];
      this.weekCurrentArr = [];
      this.weekDiffArr = []

      this.formDataMonth.periodsList.forEach((periodsItem, periodsIndex) => {
        let weekTargetData = {
          number: 0,
          price: 0,
        }
        let weekCurrentData = {
          number: 0,
          price: 0,
        }
        // console.log(periodsItem.totalNumberStage)
        weekTargetData.number = Number(periodsItem.totalNumberStage);
        weekTargetData.price  = Number(periodsItem.totalPriceStage);
        this.weekTargetArr.push(weekTargetData);
        
        periodsItem.periodsItem.forEach(productItem => {
          console.log(productItem)
          weekCurrentData.number = Number(productItem.totalNumber)
          weekCurrentData.price = Number(productItem.totalNumber) * Number(productItem.productPrice)
          this.weekCurrentArr.push(weekCurrentData)

          this.originProductNumber += Number(productItem.totalNumber)
          productItem.originRemainingNum = productItem.remainingNum
          console.log(this.originProductNumber)
        })
      })



      // console.log(this.weekTargetArr)
      // console.log(this.weekCurrentArr)
      for(let i=0; i<this.weekTargetArr.length; i++) {
        let obj = {
          number: 0,
          price: 0,
        }
        obj.number = this.weekTargetArr[i].number - this.weekCurrentArr[i].number
        obj.price  = this.weekTargetArr[i].price  - this.weekCurrentArr[i].price
        this.weekDiffArr.push(obj);
      }
      console.log(this.weekDiffArr)

    

      console.log(this.currentWeek)
    }

    
  },
  created() {
    this.jwtAuth = JSON.parse(sessionStorage.getItem('jwtAuth'));
    let monthTargetData = JSON.parse(sessionStorage.getItem('monthTargetData'));
    // console.log(monthTargetData.schoolId);
    if(monthTargetData) {
      this.formDataMonth.schoolId = monthTargetData.schoolId
      this.changeMonthSchool(monthTargetData.schoolId);
    }
    this.initSchoolList('');
  },
  methods: {
    ...mapActions([
      "formGet",
      "post"
    ]),

    previewPage() {
      this.previewStatus = true;
    },

    getDiffValue() {
      
    },

    saveData() {
      let data = JSON.stringify(this.formDataMonth);
      sessionStorage.setItem('monthTargetData', data);
      this.$message.success('已保存');

      console.log(JSON.parse(sessionStorage.getItem('monthTargetData')))
    },

    submitAddMonth() {
      let productName = '';
      let data = {}
      Object.assign(data, this.formDataMonth);

      

      // data.schoolName = this.schoolName;
      data.totalNumberMonth = this.computedMonthData.number.toString();
      data.totalPriceMonth = this.computedMonthData.price.toString();
      

      this.getWeekCountInMonth(this.formDataMonth.financialYear, this.formDataMonth.financialMonth)
      console.log(this.weekDateArr)
      console.log(data)

      data.periodsList.forEach((item, index) => {
        item.week = this.weekDateArr[index].join('~');
      })


      /**
       * 验证 所有顾问之和 是否 等于 目标设置
       */
      let periodsList = data.periodsList
      outer:
      for(let i=0; i<periodsList.length; i++) {
        let periodsItem = periodsList[i].periodsItem
        for(let j=0; j<periodsItem.length; j++) {
          let productTotalNumber = periodsItem[j].totalNumber;
          let personTotalNum = 0;

          for(let k=0; k<periodsItem[j].peopleList.length; k++) {
            personTotalNum += Number(periodsItem[j].peopleList[k].fullNumber)
          }

          if(personTotalNum != productTotalNumber) {
            // console.log(i)
            // console.log(j)
            this.$message.error(`第${i+1}期 - 课程${j+1} 课程顾问人数之和与目标不符，请检查数据`)
            return false;
            break outer;
          }

        }
      }



      // data.periodsList.forEach((item, index) => {
      //   console.log(item);    // 每期
      //   item.periodsItem.forEach((pruductItem, productIndex) => {
      //     console.log(pruductItem)
      //   })
      // })


      console.log(data);
      // return false;
      
      this.post({
        API: 'insertMonth',
        data: data
      }).then(res => {
        if(res == 1) {
          this.$message.success('新增成功');
          this.popupState.showStatusMonthly = false
          sessionStorage.removeItem('monthTargetData')
          this.$emit('updateMonthData')
        }
      }).catch(err => {
        console.log(err);
        this.$message.error(err);
      })
    },
    submitEditMonthPeople() {
      let data = this.formDataMonth;

      data.totalNumberMonth = this.computedMonthData.number.toString();
      data.totalPriceMonth = this.computedMonthData.price.toString();

      data.dataId = this.formDataMonth.targetMonthId

      this.formDataMonth.periodsList[this.currentWeek].totalNumberStage = this.computedWeekData.number.toString()
      this.formDataMonth.periodsList[this.currentWeek].totalPriceStage  = this.computedWeekData.price.toString()

      this.post({
        API: 'updateMonth',
        data: data
      }).then(res => {
        if(res == 1) {
          this.$message.success('修改成功');
          this.popupState.showStatusMonthly = false;
          this.$emit('updateMonthData')
        }
      }).catch(err => {
        this.$message.error(err);
      })
    },

    changePersonNum(e, index, productIndex, personIndex) {
      /**
       * e:            人数
       * index:        每期索引
       * productIndex: 产品索引
       * personIndex:  员工索引
       */

     

      let personItem = this.formDataMonth.periodsList[index].periodsItem[productIndex].peopleList[personIndex];
      let rate = this.formDataMonth.periodsList[index].periodsItem[productIndex]

      /**
       * 试听：auditionNumber
       * 定金：earnestNumber
       * 有效单：effectiveSingular
      */
      
      console.log(rate.signRate)
      // personItem. 签单

      rate.signRate = Number(rate.signRate)
      rate.earnestRate = Number(rate.earnestRate)
      rate.auditionRate = Number(rate.auditionRate)

      if(rate.signRate && rate.earnestRate && rate.auditionRate) {
        personItem.fullNumber = e || '0';
        personItem.earnestNumber = Math.ceil(e / (Number(rate.signRate) / 100)).toString() || '0';
        personItem.auditionNumber = Math.ceil(Math.ceil(e / (Number(rate.signRate) / 100)) / (Number(rate.earnestRate) / 100)).toString() || '0';
        personItem.effectiveSingular = Math.ceil(Math.ceil(Math.ceil(e / (Number(rate.signRate) / 100)) / (Number(rate.earnestRate) / 100)) / (Number(rate.auditionRate) / 100)).toString() || '0';
      }else{
        personItem.fullNumber = e || '0';
        personItem.earnestNumber = '0'
        personItem.auditionNumber = '0'
        personItem.effectiveSingular = '0'
      }

        // fullNumber: fullNumber,
        // earnestNum: Math.ceil((fullNumber / Number((rateInfo.signRate) / 100))),
        // auditionNum: Math.ceil(Math.ceil((fullNumber / Number((rateInfo.signRate) / 100))) / (Number(rateInfo.earnestRate) / 100)),
        // effectiveSingular: Math.ceil(Math.ceil(Math.ceil((fullNumber / Number((rateInfo.signRate) / 100))) / (Number(rateInfo.earnestRate) / 100)) / (Number(rateInfo.auditionRate) / 100)), 
      
      // personItem.fullNumber = e.toString() || '0';
      // personItem.auditionNumber = Math.ceil(e * (Number(rate.auditionRate) / 100)).toString() || '0';
      // personItem.earnestNumber = Math.ceil(Math.ceil(e * (Number(rate.auditionRate) / 100)) * (Number(rate.earnestRate) / 100)).toString() || '0';
      // personItem.effectiveSingular = Math.ceil(Math.ceil(Math.ceil(e * (Number(rate.auditionRate)/ 100)) * Number((rate.earnestRate) / 100)) * (Number(rate.signRate) / 100)).toString() || 0;

      // console.log(personItem.fullNumber)
      // console.log(personItem.auditionNumber)
      // console.log(personItem.earnestNumber)
      // console.log(personItem.effectiveSingular)

    },

    // 显示转换率
    checkRate(index, productIndex) {
      this.showCheckRate = true;
      let info = this.formDataMonth.periodsList[index].periodsItem[productIndex]
      console.log(info);
      this.rateInfo = {
        auditionRate: info.auditionRate || 0,
        earnestRate: info.earnestRate || 0,
        signRate: info.signRate || 0,
      }
    },

    // 显示详情
    personDetail(index, productIndex, personIndex) {
      this.showPersonDetail = true;
      let rateInfo = this.formDataMonth.periodsList[index].periodsItem[productIndex];
      let fullNumber = Number(this.formDataMonth.periodsList[index].periodsItem[productIndex].peopleList[personIndex].fullNumber);

      // console.log(Boolean(0))
      // console.log(rateInfo.earnestRate)
      // console.log(rateInfo.auditionRate)
      rateInfo.signRate = Number(rateInfo.signRate)
      rateInfo.earnestRate = Number(rateInfo.earnestRate)
      rateInfo.auditionRate = Number(rateInfo.auditionRate)

      if(rateInfo.signRate && rateInfo.earnestRate && rateInfo.auditionRate) {
        this.detailInfo = {
          fullNumber: fullNumber,
          earnestNum: Math.ceil((fullNumber / Number((rateInfo.signRate) / 100))),
          auditionNum: Math.ceil(Math.ceil((fullNumber / Number((rateInfo.signRate) / 100))) / (Number(rateInfo.earnestRate) / 100)),
          effectiveSingular: Math.ceil(Math.ceil(Math.ceil((fullNumber / Number((rateInfo.signRate) / 100))) / (Number(rateInfo.earnestRate) / 100)) / (Number(rateInfo.auditionRate) / 100)), 

          // fullNumber: fullNumber, 
          // auditionNum: Math.ceil(fullNumber * Number((rateInfo.auditionRate) / 100)),
          // earnestNum: Math.ceil(Math.ceil(fullNumber * Number((rateInfo.auditionRate) / 100)) * Number((rateInfo.earnestRate) / 100)),
          // effectiveSingular: Math.ceil(Math.ceil(Math.ceil(fullNumber * (Number(rateInfo.auditionRate)/ 100)) * Number((rateInfo.earnestRate) / 100)) * (Number(rateInfo.signRate) / 100))
          // effectiveSingular: Math.ceil(Math.ceil(Math.ceil(fullNumber * Number((rateInfo.auditionRate) / 100)) * Number((rateInfo.earnestRate) / 100)) * Number((rateInfo.signRate) / 100)),
        }
      }else{
        this.detailInfo = {
          fullNumber: fullNumber,
          earnestNum: '0',
          auditionNum: '0',
          effectiveSingular: '0', 
        }
      }

      console.log(this.detailInfo)
    },
    
    initSchoolList(btnId) {
      let accountId
      this.jwtAuth.schoolId == '' ? accountId = '' : accountId = this.jwtAuth.accountId
      this.post({
        API: 'queryAllSchool',
        data: {
          accountId: accountId,
          menuId: btnId || this.$route.name,
          schoolIds: this.jwtAuth.schoolId.split(','),
        }
      }).then(res => {
        
        if(btnId) {
          this.powerSchoolList = res
          console.log('aaaa')
          this.formDataMonth.schoolId = this.powerSchoolList[0].schoolId
          this.changeMonthSchool(this.formDataMonth.schoolId)
          
        }else{
          this.schoolList = res
        }
      }).catch(err => {
        this.$message.error(err);
      })
    },

    

    
    getWeekCountInMonth(year,month) {
      let today = new Date();
      
      let start = new Date(year, month-1, 1); // 得到当月第一天
      let end = new Date(year, month, 0); // 得到当月最后一天
      let start_day = start.getDay(); // 当月第一天是周几
      let i
      let week_array 
      var curMonthDays = new Date(year, month, 0).getDate();   /* 返回当月的天数 */

      switch (start_day) {
        case 0: // 周日
          start_day = 7
          break;
        case 1: // 周1
          start_day = 1
          break;
        case 2: // 周2
          start_day = 2
          break;
        case 3: // 周3
          start_day = 3
          break;
        case 4: // 周4
          start_day = 4
          break;
        case 5: // 周5
          start_day = 5
          break;
        case 6: // 周6
          start_day = 6
          break;
      
        default:
          break;
      }



      // console.log(curMonthDays / 6);
      // let week
      if(start_day >= 6) {
        this.weekNum = Math.ceil(curMonthDays / 6);
      }else{
        this.weekNum = Math.floor(curMonthDays / 6);
      }

      // console.log('本月共: ' + this.weekNum)




      // document.write('本月有: ' + week + ' 周')

      let weekArr = []      // 周日的日期
      for(let i=1; i<=curMonthDays ; i++) {
        // i: 每月日期

        let day = new Date(year, month-1, i).getDay()
        // console.log(day, i)


        if(day == 0) {
          weekArr.push(i);
        }

        // console.log(weekArr);

      }

      this.weekDateArr = [];
      let arr = []


      for(let i=0; i<weekArr.length; i++) {
        let arr = []
        if(i==0) {
          arr.push(this.format(new Date(year, month-1, 1)).startTime)
          arr.push(this.format(new Date(year, month-1, weekArr[i])).endTime)
        }
        else{
          arr.push(this.format(new Date(year, month-1, weekArr[i]-6)).startTime)
          arr.push(this.format(new Date(year, month-1, weekArr[i])).endTime)
        }

        this.weekDateArr.push(arr);
      }
      if(weekArr[weekArr.length-1] !== end) {
        let arr = [];
        arr.push(this.format(new Date(year, month-1, weekArr[weekArr.length-1] + 1)).startTime)
        arr.push(this.format(end).endTime)

        this.weekDateArr.push(arr);
      }

      
      console.log(this.weekDateArr)

      this.weekNameArr = []
      this.copyWeekArr = [];

      this.copyWeekArr = this.weekDateArr.concat();

      this.copyWeekArr.forEach((item, index) => {
        let arr = [];
        item.forEach(childItem => {
          childItem = childItem.split(' ')[0];
          let week1 = childItem.split('-')[1]
          let week2 = childItem.split('-')[2]
          arr.push(week1)
          arr.push(week2)
        })

        let dayNum  = '';
        dayNum = arr[3] - arr[1] + 1
        this.weekNameArr.push(dayNum);
      })
    },
    format(date) {
      let year = date.getFullYear();

      // console.log(year);

      let month = date.getMonth()+1;
      let day = date.getDate();
      if(day < 10) {
        day = `0${day}`;
      }
      if(month < 10) {
        month = `0${month}`;
      }
      let time = {
        startTime : `${year}-${month}-${day} 00:00:00`,
        endTime: `${year}-${month}-${day} 23:59:59`
      };

      // console.log(time.startTime)

      return time
    },
    
    // 切换产品，显示产品价格;
    changeProduct(e, index, productIndex) {
      /**
       * e:            productId
       * index:        每期索引
       * productIndex: 产品索引
       */

      // console.log(e);

      let productInfo = {}
      this.post({
        API: 'queryProductTotalPrice',
        data: {
          productId: e,
          schoolId: this.formDataMonth.schoolId,
          financialMonth: this.formDataMonth.financialMonth,
          financialYear: this.formDataMonth.financialYear,
        }
      }).then(res => {
        // productInfo = res;
        // this.formDataMonth.periodsList[index].periodsItem[productIndex].productPrice = res.productPrice;
        // this.formDataMonth.periodsList[index].periodsItem[productIndex].auditionRate = res.auditionRate;
        // this.formDataMonth.periodsList[index].periodsItem[productIndex].earnestRate = res.earnestRate;
        // this.formDataMonth.periodsList[index].periodsItem[productIndex].signRate = res.signRate;
        

        this.formDataMonth.periodsList.forEach((item, index) => {
          item.periodsItem[productIndex].productId = e;
          item.totalNumberStage = '0',
          item.totalPriceStage = '0',

          // 尚余人数
          this.formDataMonth.periodsList[index].periodsItem[productIndex].remainingNum = res.remainingNum;
          this.formDataMonth.periodsList[index].periodsItem[productIndex].originRemainingNum = res.remainingNum;

          this.formDataMonth.periodsList[index].periodsItem[productIndex].productPrice = res.productPrice;
          this.formDataMonth.periodsList[index].periodsItem[productIndex].auditionRate = res.auditionRate;
          this.formDataMonth.periodsList[index].periodsItem[productIndex].earnestRate = res.earnestRate;
          this.formDataMonth.periodsList[index].periodsItem[productIndex].signRate = res.signRate;

          this.formDataMonth.periodsList[index].periodsItem[productIndex].totalNumber = 0;
        })
      }).catch(err => {
        this.$message.error(err);
      })



    },

    // 计算尚余人数
    computedRemainingNum(e, index, productIndex) {
      /**
       * productAllNum : 更改后所有产品数量之和
       * this.originProductNumber： 接口返回 产品数量之和 原始值
       * this.originRemainingNum： 接口返回 尚余数量 原始值
       */
      // console.log(this.isUpdateMonth);

      if(e == '') {
        this.formDataMonth.periodsList[index].periodsItem[productIndex].totalNumber = 0;
      }

      if(this.isUpdateMonth == 0) {     // 新增
        let productAllNum = 0;
        this.formDataMonth.periodsList.forEach(item => {
          productAllNum += Number(item.periodsItem[productIndex].totalNumber)
        })

        this.formDataMonth.periodsList.forEach(item => {
          item.periodsItem[productIndex].remainingNum = this.formDataMonth.periodsList[index].periodsItem[productIndex].originRemainingNum - productAllNum
        })
      }else{    // 编辑
        // let originNumber = this.formDataMonth.periodsList[index].periodsItem[productIndex].totalNumber
        let originRemainingNum = this.formDataMonth.periodsList[index].periodsItem[productIndex].originRemainingNum
        let productAllNum = 0;

        console.log(this.originProductNumber + ': 原始值')

        this.formDataMonth.periodsList.forEach(item => {
          productAllNum += Number(item.periodsItem[productIndex].totalNumber)
        })
        console.log(productAllNum + ': 更改后值')
        console.log(originRemainingNum + ': 原始尚余值')

        this.formDataMonth.periodsList.forEach(item => {
          item.periodsItem[productIndex].remainingNum =  originRemainingNum - (productAllNum - this.originProductNumber)
          console.log(item.periodsItem[productIndex].remainingNum)
        })
      }

      // console.log(productAllNum);
      console.log(this.formDataMonth.periodsList[index].periodsItem[productIndex]);
    },

    // 切换员工，给所有期数同产品 赋值 ID
    changePerson(e, index, productIndex, personIndex) {

      this.formDataMonth.periodsList.forEach((item, index) => {
        item.periodsItem[productIndex].peopleList[personIndex].employeesId = e
        item.periodsItem[productIndex].peopleList[personIndex].fullNumber = '0'
      })


    },

    changeMonth(e) {
      console.log(this.formDataMonth.financialYear)
      if(!this.formDataMonth.financialYear) {
        this.$message.error('请先选择学年');
        this.formDataMonth.financialMonth = ''
        return false;
      }
      // this.formDataMonth.insertBmTargetMonthList[0].bmTargetMonthChildList = []
      let year = this.formDataMonth.financialYear;
      let month = e;

      console.log('aaa')

      this.getWeekCountInMonth(year, month)

      // this.formDataMonth.insertBmTargetMonthList.length = 1;
      console.log('bbb')
      this.renderMonth();
      

      // console.log(this.formDataMonth.insertBmTargetMonthList[0].bmTargetMonthChildList)
    },
    renderMonth() {
      /**
       * 默认生成 6 * 3 的数据列表
       */
      let defaultProdcutNum = 6;
      let defaultPersonNum = 3;

      this.formDataMonth.periodsList = []

      for(let i=0; i<this.weekNum; i++) {
        let obj = {
          periodsItem: [      // 每一期里的所有数据集合
          
          ],
          sort: i,
          week: '',
        }

        for(let i=0; i<defaultProdcutNum; i++) {
          let productObj = {
            // productInfo: {
            //   productId: '',
            //   productTotalPrice: '',
            // },
            productId: '',
            productPrice: '',
            originRemainingNum: 0,
            remainingNum: 0,
            totalNumber: '',
            peopleList: [],
          }
          for(let j=0; j<defaultPersonNum; j++) {
            let personObj = {
              employeesId: '',
              effectiveSingular: '0',
              weekTargetPrice: '',
              earnestNumber: '0',
              auditionNumber: '0',
              fullNumber: '0',
            }
            productObj.peopleList.push(personObj);
          }

          obj.periodsItem.push(productObj);
        }

        this.formDataMonth.periodsList.push(obj);
      }
    },
    changeMonthSchool(e) {
      // this.schoolList.forEach(item => {
      //   if(item.schoolId == e) {
      //     this.schoolName = item.schoolName;
      //   }
      // })
      this.queryTargetPriceAndNumber(e);    // 查询年度目标
      this.queryAllProduct(e);
      this.post({
        API: 'queryPositionListBySchoolId',
        data: {
          positionCode: [2, 5],
          schoolId: e,
        }
      }).then(res => {
        this.personList = res;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    changeYear() {
      this.queryTargetPriceAndNumber();
    },

    queryAllProduct() {
      this.formGet({
        API: 'queryProductBySchool',
        data: {
          schoolId: this.formDataMonth.schoolId
        }
      }).then(res => {
        this.productList = res;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    queryTargetPriceAndNumber() {
      this.post({
        API: 'queryTargetPriceAndNumber',
        data: {
          schoolId: this.formDataMonth.schoolId,
          financialYear: this.formDataMonth.financialYear || new Date().getFullYear().toString()
        }
      }).then(res => {
        if(res) {
          this.schoolInfo = res;
        }else{
          this.schoolInfo = {}; 
        }
      }).catch(err => {
        this.$message.error(err);
      })
    },


    handleClick(tab, event) {
      console.log(this.previewStatus)
      this.currentWeek = tab.index
    },

    // 新增课程顾问
    addPerson(periodsIndex, productIndex, personIndex) {
      /**
       * periodsIndex: 每期 索引
       * productIndex: 产品 索引
       * personIndex:  员工 索引
       */
      
      this.formDataMonth.periodsList.forEach((item, index) => {
        let obj = {
          employeesId: '',
          effectiveSingular: '0',
          weekTargetPrice: '0',
          earnestNumber: '0',
          auditionNumber: '0',
          fullNumber: '0',
        }
        item.periodsItem[productIndex].peopleList.push(obj);
      })
      // this.formDataMonth.periodsList[periodsIndex].periodsItem[productIndex].peopleList.push(obj);

    },
    // 移除课程顾问
    removePerson(periodsIndex, productIndex, personIndex) {
      if(this.formDataMonth.periodsList[periodsIndex].periodsItem[productIndex].peopleList.length == 1) {
        return false;
      }

      this.formDataMonth.periodsList.forEach((item, index) => {
        item.periodsItem[productIndex].peopleList.splice(personIndex, 1);
      })

      // this.formDataMonth.periodsList[periodsIndex].periodsItem[productIndex].peopleList.splice(personIndex, 1);
    },

    removeProduct(periodsIndex, productIndex) {
      if(this.formDataMonth.periodsList[periodsIndex].periodsItem.length == 1) {
        return false;
      }

      this.formDataMonth.periodsList.forEach(item => {
        item.periodsItem.splice(productIndex, 1);
      })
      // this.formDataMonth.periodsList[periodsIndex].periodsItem.splice(productIndex, 1);
    },
    addMonthProduct(periodsIndex, productIndex) {
      

      this.formDataMonth.periodsList.forEach(item => {
        let obj = {
          productId: '',
          productPrice: '',
          totalNumber: '',
          peopleList: [
            {
              employeesId: '',
              effectiveSingular: '0',
              weekTargetPrice: '0',
              earnestNumber: '0',
              auditionNumber: '0',
              fullNumber: '0',
            },
            {
              employeesId: '',
              effectiveSingular: '0',
              weekTargetPrice: '0',
              earnestNumber: '0',
              auditionNumber: '0',
              fullNumber: '0',
            },
            {
              employeesId: '',
              effectiveSingular: '0',
              weekTargetPrice: '0',
              earnestNumber: '0',
              auditionNumber: '0',
              fullNumber: '0',
            },
            
          ]
        }
        item.periodsItem.push(obj);
      })
      // this.formDataMonth.periodsList[periodsIndex].periodsItem.push(obj);
    },

    closePopup() {

      this.popupState.showStatusMonthly = false;
      this.$emit('updateMonthStatusNum', 0)
    },
  },
  computed: {
    // 计算产品 总价
    computedProductTotalPrice() {
      return function(index, productIndex) {
        let num = Number(this.formDataMonth.periodsList[index].periodsItem[productIndex].totalNumber)
        let price = Number(this.formDataMonth.periodsList[index].periodsItem[productIndex].productPrice)
        return num * price || 0;
      }
    },

    // 计算课程顾问 总价
    computedPersonTotalPrice() {
      return function(index, productIndex, personIndex) {
        let num = Number(this.formDataMonth.periodsList[index].periodsItem[productIndex].peopleList[personIndex].fullNumber);
        let price = Number(this.formDataMonth.periodsList[index].periodsItem[productIndex].productPrice);
        this.formDataMonth.periodsList[index].periodsItem[productIndex].peopleList[personIndex].weekTargetPrice = (num * price).toString();
        return num * price || 0;
      }
    },

    // 计算 本月目标 数据
    computedMonthData: {
      get() {
        let data = {
          number: 0,
          price: 0
        };
        

        // this.formDataMonth.periodsList[index].periodsItem[productIndex].totalNumber
        this.formDataMonth.periodsList.forEach((periodsItem, periodsIndex) => {
          periodsItem.periodsItem.forEach((productItem, productIndex) => {
            data.number += Number(productItem.totalNumber) || 0;
            data.price  += (Number(productItem.productPrice) * Number(productItem.totalNumber)) || 0;

          })
        })
        

        if(this.isUpdateMonth > 0) {
          data.number += this.monthDiffValue.number;
          data.price  += this.monthDiffValue.price;
        }

        return data

      },
      set(newVal) {
        data = newVal
      }
    },

    // 计算 本期目标 数据
    computedWeekData() {
      let data = {
        number: 0,
        price: 0
      };

      this.formDataMonth.periodsList[this.currentWeek].periodsItem.forEach(item => {
        data.number += Number(item.totalNumber) || 0;
        data.price += (Number(item.productPrice) * Number(item.totalNumber)) || 0;

        if(this.isUpdateMonth > 0) {
          // console.log(this.weekDiffArr[this.currentWeek].number)
          data.number += this.weekDiffArr[this.currentWeek].number;
          data.price  += this.weekDiffArr[this.currentWeek].price;
        }
      })
      if(this.isUpdateMonth == 0) {
        this.formDataMonth.periodsList[this.currentWeek].totalNumberStage = data.number.toString() || '0'
        this.formDataMonth.periodsList[this.currentWeek].totalPriceStage = data.price.toString() || '0'
        
        
      }

      // console.log(data)


      return data
    },

    // 计算尚余人数;
    // computedRemainingNum: {
    //   get() {
    //     let data = 0

    //     this.formDataMonth.periodsList[this.currentWeek].periodsItem.forEach(item => {
    //       console.log(item);
    //     })


    //     return data
    //   },
    //   set(newVal) {
    //     data = newVal
    //   }
    // },

    // 计算天数
    computedDay() {
      return function(index) {
        // console.log(this.weekDateArr)
      }
    }


  },
  props: ['popupState', 'formDataMonth', 'isUpdateMonth'],
}
</script>